<?php

namespace Shared;

class URLManager {
    
    public static $_instance = null;
    private $Language = null;
    
    private function __construct() {}
    
    public function createPath($name, array $arg = array()) {
        // TODO REPAIR FUNCTION
        $loader = new \Symfony\Component\Routing\Loader\XmlFileLoader(new \Symfony\Component\Config\FileLocator(array($_SERVER["DOCUMENT_ROOT"] . Application::getInstance()->getDir() .  '/../Shared' . DS . 'config')));
        // TODO GET FROM CONFIG
        $routeCollection = $loader->load('routes.xml');
        $context = new \Symfony\Component\Routing\RequestContext();
        $request = \Shared\Application::getInstance()->getRequest();
        $context->fromRequest($request);
        $generator = new \Symfony\Component\Routing\Generator\UrlGenerator($routeCollection, $context);

        try {
            if (isset($arg['Language'])) {
                $this->Language = new \Shared\Main\Language;
                unset($arg['Language']);
            }
            
            $path = $generator->generate($name, $arg);
            
            $locale = $this->Language ? $this->Language->getSlug() : $request->getLocale();
            
            if (strpos($request->getPathInfo(), '/admin') !== 0) {
                $fileName = basename($request->getScriptName());
                if ($fileName == 'app.php') {
                    $scriptName = str_replace($fileName, '', $request->getScriptName());
                    $locale = $locale . '/';
                } else {
                    $locale = '/' . $locale;
                    $scriptName = $request->getScriptName();
                }
                
                $path = str_replace($scriptName, $request->getSchemeAndHttpHost() . $scriptName . $locale, $path);
            }
        } catch (\Symfony\Component\Routing\Exception\RouteNotFoundException $Ex) {
            \Shared\Application::getInstance()->createNotFound();
        }
        if (!$path) {
            \Shared\Application::getInstance()->createNotFound();
        }

        return $path;
    }
    
    public static function getInstance() {
        if (self::$_instance == null) {
            self::$_instance =  new self;
        }
        
        return self::$_instance;
    }
}
